import { createSlice } from '@reduxjs/toolkit'
import {
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons'
const initialState = {
  token: localStorage.getItem('token') || '',
  role: localStorage.getItem('role') || '',
  userInfo: localStorage.getItem('userInfo')
    ?
    JSON.parse(localStorage.getItem('userInfo'))
    :
    {},
  menus: [
    {
      key: '/dashBoard',
      icon: <UserOutlined />,
      roles: ['*'],
      label: '仪表盘',
    },
    {
      key: 'items',
      icon: <VideoCameraOutlined />,
      roles: ['admin', 'a', 'b'],
      label: '商品管理',
      children: [
        {
          key: '/itemLists',
          roles: ['admin', 'a', 'b'],
          label: '商品列表',
        },
        {
          key: '/cateLists',
          roles: ['admin', 'a', 'b'],
          label: '商品分类列表',
        }
      ]
    },
    {
      key: '/userInfo',
      icon: <UploadOutlined />,
      roles: ['admin', 'a', 'b'],
      label: '个人中心',
    },
    {
      key: '/setting',
      icon: <UploadOutlined />,
      roles: ['a', 'b'],
      label: '设置'
    }
  ]
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    userLogin: (state, action) => {

      const { role, token, userInfo } = action.payload;
      state.token = token;
      state.role = role;
      state.userInfo = userInfo;
    },
    filterMenu: (state) => {
      const role = state.role;
      // 对于侧边导航进行过滤
      state.menus = state.menus.filter(menu => {
        return (menu.roles.includes('*') || menu.roles.includes(role))
      })
      state.menus.forEach(menu => {
        if (menu.children) {
          menu.children = menu.children.filter(subMenu => (subMenu.roles.includes('*') || subMenu.roles.includes(role)))
        }
      })
    }
  }
})

// Action creators are generated for each case reducer function
export const { userLogin, filterMenu } = userSlice.actions

export default userSlice.reducer